package org.thomias.exo2.ftp;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.sql.Timestamp;
import java.util.Date;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

public class FTP {

	private static FTPClient ftp = null;

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			ftp = new FTPClient();
			ftp.connect("127.0.0.1");
			ftp.enterLocalPassiveMode();
			ftp.login("Yannis", "k");

			int reply = ftp.getReplyCode();
			if (FTPReply.isPositiveCompletion(reply)) {
				System.out.println("Connexion sucess");
				FTPFile[] files = ftp.listFiles();
				for (FTPFile file : files) {
					println(file.getName());
				}

				upload("Yannis");
			} else {
				println("Connexion failed");
			}
			println("Disconnecting...");
			ftp.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private static void upload(String name) {
		FileInputStream fileIn = null;
		FileOutputStream fileOut = null;
		Date date = new Date();
		try {
			String fileDir = name + "_"
					+ new Timestamp(date.getTime()).getTime() + ".txt";
			try {

				println("Reading/Creating : " + fileDir + "...");
				fileOut = new FileOutputStream(fileDir);
				fileOut.write(new String("Hello World").getBytes());

				println("Uploading : " + fileDir + "...");
				fileIn = new FileInputStream(fileDir);
				ftp.storeFile(fileDir, fileIn);

			} finally {
				fileOut.close();
				fileIn.close();
			}
			new File(fileDir).delete();
			println("Deleting " + fileDir + "...");
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private static void println(String msg) {
		System.out.println(msg);

	}

}
